var that;
// 最大行数
var max_row_height = 5;
// 行高
var cart_offset = 90;
// 底部栏偏移量
var food_row_height = 49;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    "seller":{
      "headerImg":"/static/images/order.png",
      "headerTxt":{
        "txt":"全场七折，这场活动为期三天，全部包邮",
        "phone":"13666789986"
      }
    },
    "imageIp": getApp().globalData.imageIp,
    "shop":"",
    "categoryObjects":["全部"],
    "categoryId": "",
    "categoryStates": "",
    "goods":"",
    "cartData":"",

     inputVal: '',   // 搜索框输入的值
        currentCategory: 0,
        pageSize: 10,
        pageNum: 1,
        goods: [],
        addGoods: [],   //上拉刷新要加入的商品，用来判断是否重复添加

        // 购物车源码开始
        categoryStates: [false, false, false, false, false, false, false],
        cartData: {},
        cartObjects: [],
        maskVisual: 'hidden',
        amount: 0,//购物车里的价格
        quantity:0,//购物车商品数量
        express_fee:1,//配送费
        // 购物车源码结束

        //选中的当前商品的index和id
        index:"",
        goodId:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    console.log(options.shop)
    this.setData({
      shop: JSON.parse(options.shop)
    });
    var shopId = this.data.shop.id;
    console.log(shopId)
    this.loadGoods(shopId);
    //请求店铺分类
    this.requestShopSort(shopId);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //判断是否要添加到购物车
    if(getApp().globalData.ifInCart){
        //添加当前商品到购物车
        this.addByGoodDetail(this.data.goodId,this.data.index);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },

  // 点击切换分类
    switchCategory: function (e) {
        // 获取分类id并切换分类
        var index = e.currentTarget.dataset.index;
        //var categoryId = that.data.categoryObjects[index].id;
        // console.log(categoryId);
    
        var categoryId = this.data.categoryObjects[index].id;   // 获取点击的分类的名字
        // if (category === '全部') {
        //     category = null;
        // }
        // 更改分类项高亮状态
        var categoryStates = that.data.categoryStates;

        // 显示顶部loading
        wx.showNavigationBarLoading();
        categoryStates = categoryStates.map(function (item, i) {
            if (index == i) {
                item = true;
            } else {
                item = false;
            }
            return item;
        });
        that.setData({
            categoryId: categoryId,
            categoryStates: categoryStates,
            pageNum: 1   // 点击分类的时候 重置页数
        });
        console.log("调用分类搜索接口")
      that.loadGoodsByClaz(categoryId);
    },

    loadGoodsByClaz(categoryId){
      wx.request({
        url: getApp().globalData.hostIp +'/goods/selectByClazId',
        method:"GET",
        data:{
          clazId:categoryId
        },
        success:function(res){
          console.log("开始打印分类查询结果")
          console.log(res)
          that.setData({
            goods:res.data.data.rows
          });
          wx.hideNavigationBarLoading();
        },
        
      })
    },

    loadGoods(shopIds){
      var that = this;
      wx.request({
        url: getApp().globalData.hostIp +"/goods/selectByShopIds",
        method:"GET",
        header: {
          'content-type': 'application/json' // 默认值
        },
        data:{
          shopIds: 2,
          offset:0,
          limit:10
          // sort:"id",
          // order:"id"
        },
        success:function(res){
          console.log(res)
          that.setData({
            goods:res.data.data.rows
          })
        }
      })
    },


    // 跳转到订单详情页
    viewOrder() {
        wx.navigateTo({
            url: '/pages/sellbook/seller/order/order'
        })
    },

    // 跳转到search页面
    navigateToSearch() {
        wx.navigateTo({
            url: '/pages/sellbook/seller/search/search'
        })
    },

    // 获取商家配送费等信息
    loadSeller(id) {   // 因为 商铺id 改为了 学校id  所以这个方法有点问题 以后再调试
        let reg = new RegExp(/,|，|\\s+/g);
        let categoryArr = [];

        wx.request({
            url: getApp().globalData.hostIp + '/schoolShop/findPageSchoolShop',
            method: 'POST',
            data: {
                schoolId: id
            },
            success: (res) => {
                console.log('获取商家配送费信息成功');
                console.log(res);

                if (res.data.list.length != 0) {
                    categoryArr.push('全部');   // 全部分类为固定 每个开通学校都有
                    // 处理分类 用逗号分割
                    if (res.data.list[0].category) {
                        res.data.list[0].category.split(reg).forEach((val, i) => {
                            categoryArr.push($trim(val));
                        })
                    }
                    console.log(categoryArr);
                    // 对 seller 对象进行操作
                    that.setData({
                        'seller.headerTitle': res.data.list[0].name,
                        'seller.headerImg': `${getApp().globalData.imgPreUrl}${res.data.list[0].logo}`,
                        'seller.headerTxt.txt': res.data.list[0].description === null ? '暂无描述' : res.data.list[0].description,
                        'seller.headerTxt.phone': res.data.list[0].phone,
                        'seller.express_fee': res.data.list[0].sendFee === null ? 0 : res.data.list[0].sendFee,
                        'seller.buyBookRate': parseFloat(res.data.list[0].buyBookRate),
                        categoryObjects: categoryArr,
                    });

                    // 设置页面顶部 navigation title文字
                    wx.setNavigationBarTitle({
                        title: res.data.list[0].name,
                    })
                } else {
                    wx.request({
                        url: getApp().globalData.hostIp + '/schoolShop/findPageSchoolShop',
                        method: 'POST',
                        data: {
                            schoolId: '969ce78987c94f0bb6096c56654c6ac4'
                        },
                        success: (res) => {
                            // 处理分类 用逗号分割
                            //res.data.list[0].category.split(reg).forEach((val, i) => {
                                // let tempObj = {};
                                // tempObj = ;
                                //categoryArr.push($trim(val));
                            //})
                            //console.log(categoryArr);
                            // 对 seller 对象进行操作
                            console.log('获取未开通学校信息成功');
                            console.log(res);
                            that.setData({
                                'seller.headerTitle': res.data.list[0].name,
                                'seller.headerImg': `${getApp().globalData.imgPreUrl}${res.data.list[0].logo}`,
                                'seller.headerTxt.txt': res.data.list[0].description,
                                'seller.headerTxt.phone': res.data.list[0].phone,
                                'seller.express_fee': res.data.list[0].sendFee,
                                'seller.buyBookRate': parseFloat(res.data.list[0].buyBookRate),
                                categoryObjects: categoryArr,
                            });

                            // 设置页面顶部 navigation title文字
                            wx.setNavigationBarTitle({
                                title: res.data.list[0].name,
                            })
                        }
                    })
                }

                that.loadBooks();   // 加载初始书籍
            },

            fail: (err) => {
                console.log('获取商家配送费信息失败');
                console.log(err);
            }
        })
    },

    // 打电话
    phoneCall() {
        wx.makePhoneCall({
            phoneNumber: that.data.seller.headerTxt.phone,
        })
    },


    // 获取input的值
    inputTyping(e) {
        this.setData({
            inputVal: e.detail.value
        });
        this.search(e);
    },

    // 清空input的值
    clearInput() {
        that.setData({
            inputVal: '',
            pageNum: 1
        })

        // 清空后 请求全部分类的书 增加用户体验
        that.loadBooks();
    },

    // 搜索
    search(e) {
        console.log("触发了search事件");

        wx.request({
          url: getApp().globalData.hostIp + '/goods/selectByShopIds',
            method: "GET",
            data: {
                search: e.detail.value,
                shopIds: that.data.shop.id,
                offset: 0,
                limit:10
            },
            success: (res) => {
                console.log("success搜索");
                console.log(res);
                that.setData({
                    goods: res.data.data.rows,
                    pageNum: 1,
                    addGoods: []
                });
            },
            fail: (res) => {
                console.log("fail");
            },
            complete: (res) => {
                console.log("complete");
            }
        });
    },



    // 源码开始

    loadBooks: function (category) {
        category = category || null;   // 不传的话 默认为 加载全部分类的书籍
        // console.log('我是分类');
        // console.log(category);
        wx.request({
            url: getApp().globalData.hostIp + '/merchantBook/findPageMerchantBook',
            method: "POST",
            data: {
                schoolId: that.data.seller.id,
                sort: category,
                shelfFlag: 1,
                pageNum: that.data.pageNum,
                pageSize: that.data.pageSize
            },

            success: (res) => {
                console.log('按分类加载书籍成功');
                console.log(res);

                res.data.list.forEach((item, i) => {
                    item.secondPrice = parseFloat((item.prePrice * that.data.seller.buyBookRate).toFixed(2));  
                })


                // 将结果 放入 用于渲染右侧结构的数组
                that.setData({
                    books: res.data.list,
                    addGoods: []
                });

                // 隐藏顶部loading
                wx.hideNavigationBarLoading();
            },

            fail: (err) => {
                console.log('按分类加载书籍失败');
                console.log(err);
            }
        })

    },

    // 点击切换分类
    // switchCategory: function (e) {
    //     // 获取分类id并切换分类
    //     var index = e.currentTarget.dataset.index;
    //     //var categoryId = that.data.categoryObjects[index].id;
    //     // console.log(categoryId);
    
    //     var category = this.data.categoryObjects[index];   // 获取点击的分类的名字
    //     if (category === '全部') {
    //         category = null;
    //     }
    //     // 更改分类项高亮状态
    //     var categoryStates = that.data.categoryStates;

    //     // 显示顶部loading
    //     wx.showNavigationBarLoading();

    //     categoryStates = categoryStates.map(function (item, i) {
    //         if (index == i) {
    //             item = true;
    //         } else {
    //             item = false;
    //         }
    //         return item;
    //     });
    //     that.setData({
    //         category: category,
    //         categoryStates: categoryStates,
    //         pageNum: 1   // 点击分类的时候 重置页数
    //     });
    //     that.loadBooks(category);
    // },

    // 结算
    checkout: function () {
        // 将对象序列化
        var cartObjects = [];
        let bookTitleArr = [];
        let bookIdArr = [];
        let bookPriceArr = [];
        let detailArr = [];
        console.log('cartObjects');
        console.log(that.data.cartObjects);
        that.data.cartObjects.forEach(function (item, index) {
            var cart = {
                id: item.book.id,
                title: item.book.title,
                price: item.book.secondPrice,
                quantity: item.quantity,
                store: item.book.store
            };

            for(let i = 0 ; i < item.quantity; i++) {
                let tempDetailObj = {
                    bookId: item.book.id,
                    soldPrice: item.book.secondPrice
                }
                
                bookIdArr.push(item.book.id);
                bookPriceArr.push(item.book.secondPrice);
                detailArr.push(tempDetailObj)
            }
            bookTitleArr.push(item.book.title);
            cartObjects.push(cart);
        });

        that.setData({
            'payObj.orderInfo': cartObjects,
            'payObj.totalPrice': (parseFloat(that.data.amount) + parseFloat(that.data.seller.express_fee)).toFixed(2),
            'payObj.allBookTitle': bookTitleArr,
            'payObj.allBookId': bookIdArr,
            'payObj.allBookPrice': bookPriceArr,
            'payObj.detail': detailArr
        })

        let orderDetail = JSON.stringify(this.data.payObj);

        // 跳转到地址填写页面
        wx.navigateTo({
            url: '/pages/sellbook/seller/sureBuyBook/sureBuyBook?orderDetail=' + orderDetail,
        })

        console.log('处理好的结算数据')
        console.log(that.data.payObj)
        console.log('amount')
        console.log(that.data.amount)
        console.log('购物车');
        console.log(cartObjects);
        console.log('订单详情');
        console.log(that.data.payObj.detail);
    },

    // 加
    add: function (e) {
        // 所点书籍id
        var bookId = e.currentTarget.dataset.bookId;
        let bookIndex = e.currentTarget.dataset.bookIndex;
        // console.log(bookId);
        // 读取目前购物车数据
        var cartData = that.data.cartData;
        console.log(cartData)
        // 获取当前商品数量
        var bookCount = cartData[bookId] ? cartData[bookId] : 0;
        // 自增1后存回
        cartData[bookId] = ++bookCount;//这样的方式也可以创建数组
        console.log(cartData)
        // 设值到data数据中
        that.setData({
            cartData: cartData
        });
      
        // 转换成购物车数据为数组
        that.cartToArray(bookId, bookIndex);
    },

     // 通过商品详情添加
    addByGoodDetail: function (bookId,bookIndex) {
        // 所点书籍id
        // var bookId = e.currentTarget.dataset.bookId;
        // let bookIndex = e.currentTarget.dataset.bookIndex;
        // console.log(bookId);
        // 读取目前购物车数据
        var cartData = that.data.cartData;
        console.log(cartData)
        // 获取当前商品数量
        var bookCount = cartData[bookId] ? cartData[bookId] : 0;
        // 自增1后存回
        cartData[bookId] = ++bookCount;//这样的方式也可以创建数组
        console.log(cartData)
        // 设值到data数据中
        that.setData({
            cartData: cartData
        });
      
        // 转换成购物车数据为数组
        that.cartToArray(bookId, bookIndex);
    },

    // 减
    subtract: function (e) {
        // 所点商品id
        var bookId = e.currentTarget.dataset.bookId;
        let bookIndex = e.currentTarget.dataset.bookIndex;
        // 读取目前购物车数据
        var cartData = that.data.cartData;
        // 获取当前商品数量
        var bookCount = cartData[bookId];
        // 自减1
        --bookCount;
        // 减到零了就直接移除
        if (bookCount == 0) {
            delete cartData[bookId]
        } else {
            cartData[bookId] = bookCount;
        }
        // 设值到data数据中
        that.setData({
            cartData: cartData
        });
        // 转换成购物车数据为数组
        that.cartToArray(bookId, bookIndex);
    },
    cartToArray: function (bookId, bookIndex) {
        // 需要判断购物车数据中是否已经包含了原商品，从而决定新添加还是仅修改它的数量
        var cartData = that.data.cartData;
        var cartObjects = that.data.cartObjects;
        
        //从数组找到该商品，并修改它的数量
        for (var i = 0; i < cartObjects.length; i++) {
            if (cartObjects[i].good.id == bookId) {
                // 如果是undefined，那么就是通过点减号被删完了
                if (cartData[bookId] == undefined) {
                    cartObjects.splice(i, 1);
                } else {
                    cartObjects[i].quantity = cartData[bookId];
                  console.log("打印goods[index]")
                  console.log(that.data.goods[bookIndex])
                    cartObjects[i].money = (that.data.goods[bookIndex].minPrice * cartData[bookId]).toFixed(2);
                }
                that.setData({
                    cartObjects: cartObjects
                });
                // 成功找到直接返回，不再执行添加
                that.amount();
                return;
            }
        }
        // 添加商品到数组
        var cart = {};
        cart.good = that.data.goods[bookIndex];
        console.log("打印goods[index]")
      console.log(that.data.goods[bookIndex])
      cart.quantity = cartData[bookId];
      cart.money = (that.data.goods[bookIndex].minPrice * cartData[bookId]).toFixed(2);
      console.log(cart.money)
        cartObjects.push(cart);
        that.setData({
            cartObjects: cartObjects
        });
        console.log(cartObjects)
        // 因为请求网络是异步的，因此汇总在此，上同
        that.amount();
    },

    cascadeToggle: function () {
        //切换购物车开与关
        // console.log(that.data.maskVisual);
        if (that.data.maskVisual == 'show') {
            that.cascadeDismiss();
        } else {
            that.cascadePopup();
        }
    },
    cascadePopup: function () {
        // 购物车打开动画
        var animation = wx.createAnimation({
            duration: 300,
            timingFunction: 'ease-in-out',
        });
        that.animation = animation;
        // scrollHeight为商品列表本身的高度
        var scrollHeight = (that.data.cartObjects.length <= max_row_height ? that.data.cartObjects.length : max_row_height) * food_row_height;
        // cartHeight为整个购物车的高度，也就是包含了标题栏与底部栏的高度
        var cartHeight = scrollHeight + cart_offset;
        animation.translateY(- cartHeight).step();
        that.setData({
            animationData: that.animation.export(),
            maskVisual: 'show',
            scrollHeight: scrollHeight,
            cartHeight: cartHeight
        });
        // 遮罩渐变动画
        var animationMask = wx.createAnimation({
            duration: 150,
            timingFunction: 'linear',
        });
        that.animationMask = animationMask;
        animationMask.opacity(0.8).step();
        that.setData({
            animationMask: that.animationMask.export(),
        });
    },
    cascadeDismiss: function () {
        // 购物车关闭动画
        that.animation.translateY(that.data.cartHeight).step();
        that.setData({
            animationData: that.animation.export()
        });
        // 遮罩渐变动画
        that.animationMask.opacity(0).step();
        that.setData({
            animationMask: that.animationMask.export(),
        });
        // 隐藏遮罩层
        that.setData({
            maskVisual: 'hidden'
        });
    },
    amount: function () {
        var cartObjects = that.data.cartObjects;
        var amount = 0;
        var quantity = 0;
        console.log(cartObjects)
        cartObjects.forEach(function (item, index) {
            amount += item.quantity * item.good.minPrice;
            quantity += item.quantity;
        });
      console.log(amount)
        that.setData({
            amount: amount.toFixed(2),
            quantity: quantity
        });
        
        console.log(that.data.amount)
    },
    // 源码结束


    // 清空购物车的动画   主要是为了修改动画时间
    clearCartAnimation() {
        let animation = wx.createAnimation({
            duration: 1000,
            timingFunction: 'ease-in-out'
        });
        that.animation = animation;
        animation.translateY(that.data.cartHeight).step();   // 购物车关闭动画
        that.setData({
            animationData: that.animation.export()
        });
        // 遮罩渐变动画
        that.animationMask.opacity(0).step();
        that.setData({
            animationMask: that.animationMask.export(),
        });
        // 隐藏遮罩层
        that.setData({
            maskVisual: 'hidden'
        });
    },


    // 清空购物车
    clearCart() {
        that.setData({
            cartObjects: [],
            cartData: {},
            amount: 0,
            quantity: 0
        });

        that.clearCartAnimation();
        
    },

    // 跳转到客服页面
    navigateToChat() {
        wx.navigateTo({
            url: '/pages/sellbook/seller/chat/chat',
        })
    },

    //请求店铺分类
    requestShopSort(shopId){
      wx.request({
        url:getApp().globalData.hostIp+"//claz/selectByShopId",
        method:"GET",
        header:{
          "content-type":"application/json"
        },
        data:{
          shopId:shopId
        },
        success:function(res){
          console.log(res)
          that.setData({
            categoryObjects:res.data.data
          })
        }
      });
    },


    //跳转到商品详情页
    goodDetail(e){
        console.log(e)
        //1.获取商品在数组里的索引
        var index = e.currentTarget.dataset.index;
        //2.获取商品id
        var id = this.data.goods[index].id;

        this.setData({
            index:index,
            goodId:id
        })
        //3.跳转到good-detail页面，带有参数id
        wx.navigateTo({
            url:"/pages/index/shop/good-detail/good-detail?id="+id
        })
    }
})